/**
 * 螺旋矩阵
 * 1.循环不变量，左闭右开原则
 * 2.while循环，停止条件：左边界超过右边界，上边界超过下边界
 * 3.收缩圈数
 * 4.特殊情况;[[6,9,7]],[[7],[9],[6]],这时就需要判断长度
 */

function spiralOrder(matrix) {
  // 如果传入的不是矩阵，则返回空数组
  if (!matrix.length || !matrix[0].length) {
    return [];
  }

  let result = [];
  // 行和列
  let row = matrix.length;
  let col = matrix[0].length;
  // 初始化四个边界
  let leftTop = 0;
  let rightTop = row - 1;
  let leftBottom = 0;
  let rightBottom = col - 1;

  while (leftTop <= rightTop && leftBottom <= rightBottom) {
    let startX = leftTop;
    let startY = leftBottom;

    // 从左到右
    for (; startY < rightBottom; startY++) {
      if (result.length === col * row) break;

      result.push(matrix[startX][startY]);
    }

    // 从上到下
    for (; startX < rightTop; startX++) {
      if (result.length === col * row) break;

      result.push(matrix[startX][startY]);
    }

    // 从右往左
    for (; startY > leftBottom; startY--) {
      if (result.length === col * row) break;

      result.push(matrix[startX][startY]);
    }

    // 从下到上
    for (; startX > leftTop; startX--) {
      if (result.length === col * row) break;

      result.push(matrix[startX][startY]);
    }

    // 如果leftTop 和 rightTop相等且长度等二维矩阵不相等，则取中间值
    if (leftTop === rightTop && result.length !== col * row) {
      result.push(matrix[startX][startY]);
    }

    // 更新边界
    leftTop++;
    rightTop--;
    leftBottom++;
    rightBottom--;
  }

  return result;
}
// const matrix = [
//   [1, 2, 3],
//   [4, 5, 6],
//   [7, 8, 9],

// ];
const matrix = [[6, 9, 7]];
const res = spiralOrder(matrix);
console.log(res);
